/*
 * Copyright (C) 2012 Google Inc.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Connects listeners to the buttons in the popup window.
 * Most buttons call functions that are organized into separate files.
 *   googletvremote_controller.js - Creates the plugin.
 *   discovery_client_controll.js - Finds Google TVs on the local network.
 *   pairing_session_controller.js - Pairs to a Google TV.
 *   anymote_session_controller.js - Communicates with Google TV after paired.
 */


/** Key used by localStorage to store ip addresses of paired Google TVs. */
STORAGE_KEY_PAIRED_DEVICES = 'paired-devices';


/** Register listeners for the button elements. */
window.onload = function() {
  // 1. Create the plugin embed and initialize.
  document.getElementById('initialize-plugin')
      .addEventListener('click', googletvremoteInitializePlugin);

  // 2. Start an Anymote session with an existing connection.
  document.getElementById('restablish-existing-connections')
      .addEventListener('click', anymoteConnectToExistingDevice);
  document.getElementById('clear-devices')
      .addEventListener('click', function() {
        localStorage.removeItem(STORAGE_KEY_PAIRED_DEVICES);
        updatePairedDevicesList();
      });

  // New connections (if necessary).
  // 3a. Discovery client.
  document.getElementById('start-discovery')
      .addEventListener('click', startDiscoveryClient);
  document.getElementById('stop-discovery')
      .addEventListener('click', stopDiscoveryClient);

  // 3b. Pairing session.
  document.getElementById('pair').addEventListener('click', function() {
    pairingSessionPair(document.getElementById('ip-address').value);
    document.getElementById('challenge-field').focus();
  });
  document.getElementById('set-challenge')
      .addEventListener('click', function() {
        sendChallengeResponse(document.getElementById('challenge-field').value);
      });

  // 3c. Start Anymote session with this new device.
  document.getElementById('new-device-pair').addEventListener('click',
      function() {
        anymoteStartSession(document.getElementById('ip-address').value,
            function(e) {
              if (e.type == googletvremote.anymote.EventType.CONNECTED) {
                console.log('Successful Anymote session connection.');
              } else {
                console.log('Unsuccessful Anymote session connection.');
              }
            });
      });

  // 4. Using Anymote.
  document.getElementById('home').addEventListener('click', function() {
    sendAnymoteKeyEvent(googletvremote.anymote.KeyCode.HOME);
  });
  document.getElementById('search').addEventListener('click', function() {
    sendAnymoteKeyEvent(googletvremote.anymote.KeyCode.SEARCH);
  });
  // Extra credit - Actually sending the string 'Hello, world'.
  document.getElementById('hello-world').addEventListener('click', function() {
    sendAnymoteStringMessage('Hello, world');
  });
  // Extra credit - Fling a uri to the TV to create an intent (fun).
  document.getElementById('uri-fling').addEventListener('click', function() {
    // Urls that launch Chrome.
    sendAnymoteFling('http://code.google.com/p/google-tv-chrome-extensions/');
		//sendAnymoteFling('http://www.youtube.com/watch?v=Nli4Vy2zGYA#t=38m20s');
    //chrome.tabs.getSelected(null, function(tab) {sendAnymoteFling(tab.url);});

    // YouTube flings
    //sendAnymoteFling('vnd.youtube://Nli4Vy2zGYA'); // Extensions @ 38:20
    //sendAnymoteFling('vnd.youtube.channel://googletv');
    //sendAnymoteFling('vnd.youtube.channel://GoogleDevelopers');

    // Other apps.
    //sendAnymoteFling('tv://');
    //sendAnymoteFling('market://details?id=' +
    //    'com.google.android.apps.panoramiogtv');

    // Explicit communication with your own apps.
    // Must install Panoramio on your Google TV before next fling.
    //sendAnymoteFling('intent:#Intent;' +
    //    'component=com.google.android.apps.panoramiogtv/.ImageGrid;' +
    //    'end');
  });
  // Extra credit - Ping the Google TV to test connection status.
  document.getElementById('ping').addEventListener('click', function() {
    sendAnymotePing();
  });
  // Extra credit - Sending Dpad events using the keyboard arrow keys.
  document.body.addEventListener('keydown', function(e) {
    switch (e.keyCode) {
      case 13:
        sendAnymoteKeyEvent(googletvremote.anymote.KeyCode.DPAD_CENTER);
        break;
      case 37:
        sendAnymoteKeyEvent(googletvremote.anymote.KeyCode.DPAD_LEFT);
        break;
      case 38:
        sendAnymoteKeyEvent(googletvremote.anymote.KeyCode.DPAD_UP);
        break;
      case 39:
        sendAnymoteKeyEvent(googletvremote.anymote.KeyCode.DPAD_RIGHT);
        break;
      case 40:
        sendAnymoteKeyEvent(googletvremote.anymote.KeyCode.DPAD_DOWN);
        break;
    }
  });
  updatePairedDevicesList();

  // In a real app you'd automatically do things like creating the plugin and
  // starting an Anymote session with a paired Google TV. Additionally in a real
  // extension you could put the embed on the background page.
//  googletvremoteInitializePlugin();
//  anymoteConnectToExistingDevice();
};


/** Update the UI to display the IP address of connected devices. */
var updatePairedDevicesList = function() {
  // Start by clearing the list and removing the button, then populate.
  var pairedDeviceList = document.getElementById('paired-device-list');
  while (pairedDeviceList.hasChildNodes()) {
    pairedDeviceList.removeChild(pairedDeviceList.lastChild);
  }
  document.getElementById('clear-devices').style.display = 'none';
  var devicesInStorage = localStorage.getItem(STORAGE_KEY_PAIRED_DEVICES);
  if (devicesInStorage) {
    var pairedDevices = JSON.parse(devicesInStorage);
    for (var i = 0; i < pairedDevices.length; i++) {
      var deviceLi = document.createElement('li');
      deviceLi.innerHTML = pairedDevices[i];
      pairedDeviceList.appendChild(deviceLi);
    }
    if (pairedDevices.length > 0) {
      document.getElementById('clear-devices').style.display = 'inline-block';
    }
  }
};
